<template>
  <el-dialog
    title="分配角色"
    :visible="SetRoleDialogVisible"
    width="50%"
    @close="onclose"
    @open="handleOpen"
  >
    <el-checkbox-group v-model="checkList">
      <el-tooltip
        v-for="item in roles"
        :key="item.id"
        class="item"
        effect="dark"
        :content="item.description"
        placement="top"
      >
        <el-checkbox
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-tooltip>

    </el-checkbox-group>

    <span slot="footer" class="dialog-footer">
      <el-button @click="onclose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRolesList } from '@/api/company'
import { getUserInfoById } from '@/api/user'
import { assigningRoles } from '@/api/employees'
import { Loading } from 'element-ui'

export default {
  name: 'AssignRole',
  props: {
    SetRoleDialogVisible: {
      type: Boolean,
      require: true
    },
    currentEmployeesId: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      checkList: [],
      roles: [],
      isLoading: false
    }
  },
  created() {
    this.loadRolesList()
  },
  methods: {
    // 加载所有角色
    async loadRolesList() {
      const { total } = await getRolesList()
      const { rows } = await getRolesList({ page: 1, pagesize: total })
      this.roles = rows
    },
    // 打开的回调
    async handleOpen() {
      this.$nextTick(async() => {
        const loadingInstance = Loading.service({
          target: '.el-dialog__body'
        })
        const { roleIds } = await getUserInfoById(this.currentEmployeesId)
        this.checkList = roleIds
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close()
        })
      })
    },
    // 点击确定
    async onSave() {
      if (!this.checkList.length) return this.$message.warning('员工至少有一个角色')
      await assigningRoles({ id: this.currentEmployeesId, roleIds: this.checkList })
      this.$message.success('分配角色成功')
      this.onclose()
    },
    onclose() {
      this.$emit('update:set-role-dialog-visible', false)
      this.checkList = []
    }
  }
}
</script>

<style scoped lang='less'>

</style>
